from flask import Blueprint, jsonify, make_response
from utils.myjwt import MyJwt
from db import db
import datetime,random
from utils.captcha.captcha import Captcha
from utils.myredis import r
from utils.smscode import SmsCode
from utils.myjwt import MyJwt
from flask_restful import reqparse,Resource,Api
from flask import current_app as app,request
from job.tasks.mytask import send_message
user_blue = Blueprint('user_blue',__name__)
api=Api(user_blue)
@user_blue.route("/test")
def test():
    str = datetime.datetime.strftime(datetime.datetime.now(),'%Y-%m-%d %H:%M:%S')+"   "+request.path+"   error"
    # app.logger.error(str)
    # app.logger.info('info log')
    # app.logger.warning('warning log')
    try:
        sql = "insert into user values(0,'aa22222','abc')"
        db.update(sql)
        db.commit()
        app.logger.info(str+'加入用户成功')
    except:
        app.logger.error(str+'失败')
        db.rollback()

    return 'ok234234'


# 图片验证码


# 发送验证码视图
class SmsCodes(Resource):
    def post(self):
        # 获取手机号
        req=reqparse.RequestParser()
        req.add_argument('phone')
        args=req.parse_args()
        # 有效性验证
        rule=r'^1[3-9][0-9]{9}$'
        if not rule:
            return jsonify({
                'code':400,
                'msg':'手机号格式不匹配'
            })
        # 调用短信平台发送验证码
        code=random.randint(100000,999999)
        sdk=SmsCode().send(args['phone'],code)
        # 发送失败（重试3次）
        if not sdk:
            return jsonify({
                'code':400,
                'msg':'发送失败'
            })
        return jsonify({
                'code':200,
                'msg':'验证发送成功',
                'data':code
            })
api.add_resource(SmsCodes,'/sms')

# 登录视图
class LoginView(Resource):
    def post(self):
        req=reqparse.RequestParser()
        req.add_argument('phone')
        req.add_argument('code')
        args=req.parse_args()
        if not args['phone']:
            return jsonify({
                'code':400,
                'msg':'手机号不存在'
            })
        pho="select * from user where phone=%s"%args['phone']
        db.find(pho)
        if not pho:
            # 创建手机号和密码
            a="insert into user(id,phone) values ('1',%s)"%args['phone']
            db.update(a)
            db.commit()
            return jsonify({
                'code':200,
                'msg':'注册成功'
            })
        pho = "select * from user where phone=%s" % args['phone']
        db.find(pho)

        token=MyJwt().jwt_encode({
            'phone':args['phone']
        })
        return jsonify({
            'code':200,
            'msg':'登录成功',
            'token':token
        })
api.add_resource(LoginView,'/login')

# 生成图片验证码
@user_blue.route('/create_imagecode/')
def create_imagecode():
    uuid=request.args.get('uuid')
    name,text,image=Captcha().generate_captcha()
    res=make_response(image)
    res.headers['Content-Type']='image/jpg'
    # 存入redi
    r.set_str(uuid,text)
    return res




# 员工增加
class EmpManger(Resource):
    def post(self):
        ...

api.add_resource(EmpManger,'/emp')

@user_blue.route('empMager',methods=['POST','GET'])
def empMager():
    return 'ok'
@user_blue.route('/get_wb')
def get_wb():
    data={
        'client_id':'3674019597',


    }

